import Promise from 'bluebird';
import 'whatwg-fetch';
import princessWeight from 'pages/app/assets/images/bigo/pricess-weight.jpg';
import pricessHardback from 'pages/app/assets/images/bigo/pricess-hardback.jpg';
import ticketsBag from 'pages/app/assets/images/bigo/tickets-bag.jpg';
import pricessNormal from 'pages/app/assets/images/bigo/pricess-normal.jpg';
import photoSnh48 from 'pages/app/assets/images/bigo/snh48-photo.jpg';
import sticksSnh48 from 'pages/app/assets/images/bigo/snh48-sticks.jpg';
import whaleyVrX1 from 'pages/app/assets/images/bigo/custom-edition-vr-glasses.jpg';
import tks from 'pages/app/assets/images/tks.jpg';
import shuffle from 'lodash.shuffle';

export const lotteryRaffles = [
  {
    name: '感谢您参与',
    abbr: '感谢您参与',
    imgUrl: tks,
    bigo: false
  },
  {
    name: '官方门票袋',
    abbr: '官方门票袋',
    imgUrl: ticketsBag,
    bigo: true
  },
  {
    name: '《公主披风》生写',
    abbr: '《公主披风》生写',
    imgUrl: photoSnh48,
    bigo: true
  },
  {
    name: '官方应援荧光棒',
    abbr: '官方应援荧光棒',
    imgUrl: sticksSnh48,
    bigo: true
  },
  {
    name: '《公主披风》重磅版',
    abbr: '《公主披风》重磅版',
    imgUrl: princessWeight,
    bigo: true
  },
  {
    name: '《公主披风》精装版',
    abbr: '《公主披风》精装版',
    imgUrl: pricessHardback,
    bigo: true
  },
  {
    name: '微鲸VR眼镜',
    abbr: '微鲸VR眼镜',
    imgUrl: whaleyVrX1,
    bigo: true
  },
  {
    name: '《公主披风》标准版',
    abbr: '《公主披风》标准版',
    imgUrl: pricessNormal,
    bigo: true
  }
];

export const winnerslog = [
  '用户 18800208710 获得 官方应援荧光棒',
  '用户 18862147074 获得 官方门票袋',
  '用户 13584825867 获得 《公主披风》重磅版',
  '用户 13800711867 获得 《公主披风》生写',
  '用户 13477098134 获得 官方应援荧光棒',
  '用户 13906822467 获得 《公主披风》生写',
  '用户 13404008757 获得 官方应援荧光棒',
  '用户 13564572130 获得 官方应援荧光棒',
  '用户 13600204810 获得 《公主披风》标准版',
  '用户 18945672280 获得 官方应援荧光棒'
];

const api = 'http://storeapi.test.snailvr.com/lottery';
window.Promise = Promise;

window.$uid = '';
function object2str(params) {
  if(typeof params !== 'object') return '';
  if(Object.prototype.toString.call(params).slice(8,-1) !== 'Object') return '';
  let str ='';
  for(let i in params) {
    str +=i+'='+params[i]+'&'    
  }
  return /&$/.test(str)===true? str.slice(0, -1) : str;
}
function sortParams(str) {
  var arry = str.split('&');
  arry = arry.sort();
  return arry.join('&');
}
function signmd5(str) {
  let md5 = require('md5');  
  return md5(str+'WHALEYVR_SNAILVR_AUTHENTICATION');
}
function json(path, query = '') {
  const dataTime = Date.now() || (new Date()).getTime();
  let hash;
  if(query.length>0) {
    hash = sortParams(`timestamp=${dataTime}&domain=${location.host}&uid=${$uid}&`+query);
  } else {
    hash = sortParams(`timestamp=${dataTime}&domain=${location.host}&uid=${$uid}`);
  }
  const sign = signmd5(hash);
  return fetch(`${api}/${path}?${hash}&sign=${sign}`, { credentials: 'include' }).then((resp) => resp.json());
}

function sharejson(path, query = '') {
  return fetch(`${api}/${path}?domain=${location.host}&uid=${$uid}&${query}`, { credentials: 'include' }).then((resp) => resp.json());  
}

export function getUserInfo() {
  return json('userinfo').then(({ status, userinfo, lottery, list }) => {
    list = list || [];
    if (status === 1) {
      $uid = userinfo.uid;
      return {
        status: status,
        user: {
          uid: $uid,
          phone: userinfo.phone,
          uname: userinfo.username,
          remaining: parseInt(userinfo.times),
          hasAddress: !!userinfo.addr,
          hasLottery: !!lottery
        },
        userLottery: list.map(({ create_time, sid }) => ({
            time: handleRafflesList(create_time), 
            sid: parseInt(sid),
            raffleName: lotteryRaffles[sid].name,
            rafflePhoto: lotteryRaffles[sid].imgUrl
          }))
      };
    }
    return {
      status: status
    };
  });
}

function handleRafflesList(raf) {
  let date = [];  
  if (typeof raf !== 'string') { 
    return;
  }
  if (raf.length < 6) {
    return;
  }
  date[0] = raf.slice(4,6);
  date[1] = raf.slice(6,8);
  return `${date[0]}月${date[1]}号我抽中了`;
}

export function updateUserAddress({address, username}) {
  return json('userdetail', `address=${address}&username=${username}`);
}

export function getWinnerslog() {
  return json('winnerslog').then((log) => {
    if (log.status === 1 && log.list && log.list.length > 0) {
      return shuffle(log.list.map(({ phone, sid }) => (`用户 ${phone} 获得 ${lotteryRaffles[parseInt(sid)].name}`)).concat(winnerslog).slice(0, 10));
    }
    return shuffle(winnerslog);
  });
}

export function getCheckcode({ account, type }) {
  return json(
    'mobile',
    `account=${encodeURIComponent(account)}&type=${encodeURIComponent(type)}`
  ).then(({status, msg}) => {
    return {
      status,
      msg
    }
  });
}
export function signIn({ phone, checkcode }) {
  return json(
    'userreg',
    `phone=${encodeURIComponent(phone)}&code=${encodeURIComponent(checkcode)}`
  ).then(({ status, times, uid, isexist, addr }) => {
    if (status === 1) {
      $uid = uid;
      return {
        status,
        user: {
          phone,
          uid,
          hasAddress: !!addr,
          remaining: times
        }
      };
    }
    return {
      status,
      user: {}
    }
  });
}

const answerHash = {
  A: 0,
  B: 1,
  C: 2
};

const platformHash = {
  1: 'qq',
  2: 'weibo',
  3: 'weixin',
  4: 'weixinfriends'
};

export function share(platform) {
  return sharejson('share', `act=${platformHash[platform]}`);
}

export function lottery() {
  return json('index').then(({ status, sid, remain, shopname }) => {
    remain = parseInt(remain);
    if (typeof remain !== 'number' || remain < 0) {
      remain = -1;
    }
    if (status === 1) {
      
      return {
        status,
        sid: parseInt(sid),
        remaining: remain,
        shopname: shopname
      };
    } else {
      return {
        status,
        sid: 0,
        remaining: remain
      };      
    }
  });
}

export default {
  getUserInfo,
  getWinnerslog,
  signIn,
  lottery,
  share,
  lotteryRaffles,
  winnerslog,
  updateUserAddress,
  getCheckcode
};
